<template>
	<!-- 业主合同物业交割单 -->
	<a-modal
		:visible="visible"
		width="800px"
		class="delivery-note"
		title="物业交割单"
		centered
		@cancel="cancelHandler"
		:destroyOnClose="true"
		:maskClosable="false"
		:bodyStyle="{paddingBottom: 0}">
		<!-- <div v-if="props.isShow" class="bill-box">
			<a-select
				v-model:value="houseId"
				:options="searchOptions"
				:field-names="{label: 'enterPriseName', value: 'id'}"
				class="select"></a-select>
			<a-button :disabled="activeIndex === 0" @click="changeHouseId(-1)">上一套</a-button>
			<a-button :disabled="activeIndex === searchOptions.length - 1" @click="changeHouseId(1)">下一套</a-button>
		</div>
		<div v-if="props.isCharterSign" class="bill-box">
			<a-select
				v-model:value="houseId"
				:options="enterPriseContracList"
				:field-names="{label: 'address', value: 'id'}"
				class="select"
				@change="handlerChange($event)"></a-select>
		</div> -->
		<div class="delivery-note-module tab-box">
			<div class="d-module-title">
				<!-- <b>房屋配置</b> -->
				<b>房间固定资产配置</b>
			</div>
			<div class="right-btn">
				<a-button v-action="['mk_enterprise_assets_list_deploy']" type="link" @click="deliveryShow">仓库调配</a-button>
			</div>
			<vxe-grid ref="grid" v-bind="gridOptions">
				<template #action="{row}">
					<a v-if="hasPermissions(operation[0].action)" @click="handler(row, operation[0].field)">{{ operation[0].name }}</a>
					<a-divider type="vertical" v-if="hasPermissions(operation.map(item => item.action))" />
					<a-dropdown placement="bottom" v-if="hasPermissions(operation.map(item => item.action))">
						<a class="ant-dropdown-link">
							更多
							<down-outlined />
						</a>
						<template #overlay>
							<a-menu class="default-menu-item">
								<template v-for="(operationItem, index) in operation" :key="row.id + index">
									<a-menu-item @click="handler(row, operationItem.field)" v-if="index !== 0">
										{{ operationItem.name }}
									</a-menu-item>
								</template>
							</a-menu>
						</template>
					</a-dropdown>
				</template>
			</vxe-grid>
		</div>
		<div class="delivery-note-module">
			<div class="d-module-title">
				<b>备注</b>
			</div>
			<div>
				<a-textarea placeholder="请输入" v-model:value="modelRef.comment" show-count :maxlength="100" />
			</div>
		</div>
		<div class="delivery-note-module">
			<div class="d-module-title">
				<b>水电燃气底数(只做记录)</b>
			</div>
			<vxe-table :data="[{}]" border size="small" show-overflow>
				<vxe-column v-for="meter in modelRef.meters" :key="meter.deviceType" header-align="center">
					<template #header>
						{{ METER_DEVICE_MAP[meter.deviceType] }}
					</template>
					<template #default>
						<div class="display-flex">
							<a-input-number
								v-model:value="meter.read"
								size="small"
								:min="0"
								:precision="2"
								:controls="false"
								:bordered="false"
								placeholder="请输入底数"
								style="flex: 1" />
							<span style="align-self: center">{{ meter.suffix }}</span>
						</div>
					</template>
				</vxe-column>
			</vxe-table>
			<!-- <template v-if="baseNumbe.bindEleMater || baseNumbe.bindHotWaterMater || baseNumbe.bindClodWaterMater">
				<span
					v-if="
						[baseNumbe.eleMaterStatusName, baseNumbe.clodWaterMaterStatusName, baseNumbe.hotWaterMaterStatusName].includes(
							'离线'
						)
					"
					class="error-color">
					注：设备已离线，需要手动填写
				</span>
			</template> -->
		</div>
		<div class="delivery-note-module">
			<div class="d-module-title">
				<b>附件</b>
			</div>
			<div class="width-33">
				<a-button type="primary" block @click="operationField.attachment = true">
					<check-outlined v-if="attachments?.length" />
					<plus-outlined v-else />
				</a-button>
			</div>
		</div>
		<template #footer>
			<!-- <a-button @click="cancel">{{ houseIndex ? '上一套' : '取消' }}</a-button> -->
			<!-- {{ isSupplement ? '保存并锁定' : '保存' }} -->
			<a-button v-if="!props.isCharterSign" type="primary" @click="sendRequest">保存</a-button>
			<!-- <a-button v-if="props.isCharterSign && houseIndex !== enterPriseContracList.length - 1" type="primary" @click="checkInNext">
				确定,查看下一套
			</a-button>
			<a-button v-if="props.isCharterSign && houseIndex === enterPriseContracList.length - 1" type="primary" @click="completeSave">
				完成确定并保存
			</a-button> -->
		</template>
	</a-modal>
	<!-- 附件上传 -->
	<file-upload-dialog v-model:visible="operationField.attachment" v-model:files="attachments" />
	<select-delivery-order v-model:visible="delivery" :data="modelRef.articles" :attribution-status="1" @success="getCheckData" />
	<!-- 遗失资产 -->
	<loss-assets-dialog :data="modelData.record" v-model:visible="operationField.showLoss" @success="deleteAssetDate" />
	<!-- 报废资产 -->
	<scrap-assets-dialog :id="modelData.record.id" v-model:visible="operationField.showScrap" @success="deleteAssetDate" />
	<!-- 调配资产 -->
	<deploy-assets-dialog
		:id="modelData.record.id"
		:room-id="props.id || houseId"
		v-model:visible="operationField.showDeploy"
		@success="deleteAssetDate"
		@getWarehouseId="warehouseIdF" />
</template>
<script setup lang="ts">
	import {reactive, ref, watch, watchEffect, createVNode} from 'vue'
	import {CheckOutlined, DownOutlined, PlusOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue'
	import {VxeGridProps} from 'vxe-table'
	import {getCurEleAndWaterQuantity, getHouseDeliveryGetNoe, houseConfigGetList, houseDeliverySave} from '@/api/contract'
	import SelectDeliveryOrder from '@/components/contract/add-tenant-contract-dialog/select-delivery-order.vue'
	import LossAssetsDialog from '@/components/contract/add-tenant-contract-dialog/loss-assets-dialog.vue'
	import ScrapAssetsDialog from '@/components/contract/add-tenant-contract-dialog/scrap-assets-dialog.vue'
	import DeployAssetsDialog from '@/components/contract/add-tenant-contract-dialog/deploy-assets-dialog.vue'
	// import XEUtils from 'xe-utils'
	import {useStore} from '@/store/index'
	import {Img} from 'yuxin-base/src/types'
	import {METER_DEVICE_MAP} from '@/constant/device'
	import {defaultMeters} from '@/interface/contract'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'
	import {isLockinEnv} from 'yuxin-base/src/utils'
	import XEUtils from 'xe-utils'
	import {message, Modal} from 'ant-design-vue'

	const hasPermissions = useStore().hasPermissions

	const modelRef = reactive<any>({
		comment: null,
		attachments: [],
		articles: [],
		transferWhArticles: [],

		meters: defaultMeters()
	})

	const attachments = ref<Img[]>([])
	const grid = ref()
	const baseNumbe = ref<any>({})
	const searchOptions = ref<any>([])
	const houseId = ref<any>('')
	const activeIndex = ref<number>(-1)
	//上下切换
	const changeHouseId = num => {
		activeIndex.value = activeIndex.value + num
		houseId.value = searchOptions[activeIndex.value].id
	}

	const operationField = reactive<any>({
		showLoss: false,
		showScrap: false,
		showDeploy: false,
		attachment: false
	})
	const delivery = ref<any>(false)
	const props = defineProps<{
		// 房源ID
		id?: string
		visible: boolean
		// 合同ID
		contractId?: string
		isShow?: boolean
		delivery?: any
		isCharterSign?: boolean
		enterPriseContractHouseRoomFroms?: any
		signType?: string | number
		isResubmit?:boolean
		// 是否是补充物业交割单
		isSupplement?: boolean
	}>()

	const enterPriseContracList = ref<any>([])

	const houseIndex = ref(0)

	const checkList = reactive<any>([])

	const operation = [
		{
			name: '调配',
			field: 'deployment',
			action: ['mk_enterprise_assets_list_deploy']
		},
		{
			name: '报废',
			field: 'scrapped',
			action: ['mk_enterprise_assets_list_scrap']
		},
		{
			name: '遗失',
			field: 'lost',
			action: ['mk_enterprise_assets_list_lost']
		}
	]
	const modelData = reactive<any>({
		record: {}
	})
	const deliveryShow = () => {
		modelRef.articles = grid.value.getTableData().tableData
		delivery.value = true
	}

	const resetModelRef = () => {
		// 进来之前先把表单全部重置掉！！！
		modelRef.comment = null
		modelRef.attachments = []
		modelRef.articles = []
		modelRef.transferWhArticles = []
		modelRef.meters = defaultMeters()
		attachments.value = []
	}

	const getCheckData = (list: any) => {
		checkList.value = list
		insertEvent(-1, list)
	}
	const insertEvent = async (row: any, list: any) => {
		// const $table = grid.value
		const {row: newRow} = grid.value.insertAt(list, row)
		await grid.value.setEditCell(newRow, 'name')
	}

	const getList = (page?: any) => {
		grid.value?.commitProxy(page === 1 ? 'reload' : 'query')
	}

	const emit = defineEmits(['update:visible', 'success'])

	const cancelHandler = () => {
		prompt()
		// if (checkList.value) {
		// 	grid.value.remove(checkList.value)
		// }

		// Object.keys(operationField).forEach(key => {
		// 	operationField[key] = false
		// })
		// houseIndex.value = 0
		// houseId.value = ''
		// grid.value.remove()
		// emit('update:visible', false)
	}

	const cancel = () => {
		if (houseIndex.value === 0) {
			prompt()
			// if (checkList.value) {
			// 	grid.value.remove(checkList.value)
			// }
			// Object.keys(operationField).forEach(key => {
			// 	operationField[key] = false
			// })
			// houseIndex.value = 0
			// houseId.value = ''
			// grid.value.remove()
			// emit('update:visible', false)
		} else {
			// 执行上一套
			houseIndex.value -= 1
			houseId.value = enterPriseContracList.value[houseIndex.value]?.id

			handlerClick()
		}
	}

	const deleteAssetDate = () => {
		grid.value.remove(modelData.record)
	}
	const sendRequest = () => {
		modelRef.articles = XEUtils.clone(grid.value.getTableData().tableData, true)
		// console.log(modelRef.articles)
		modelRef.attachmentDtos = attachments.value

		// 附件列表id集合
		modelRef.attachments = JSON.stringify(attachments.value.map(o => o.id))

		// 如果是补充物业交割合同需要发这个请求
		if (props.isSupplement) {
			const _deliverInfo = {
				...modelRef,
				compactType: 3, // 合同类型-1 个人 2 企业 3 业主
				deliveryType: 1,
				houseId: props.id,
				compactId: props.contractId
			}
			houseDeliverySave(_deliverInfo).then(res => {
				message.success('操作成功')
				resetStatus()
			})
		}
		resetStatus()
	}

	const resetStatus = () => {
		emit('success', modelRef)
		Object.keys(operationField).forEach(key => {
			operationField[key] = false
		})
		checkList.value = []
		grid.value.remove()
		emit('update:visible', false)
	}


	const setEleAndWaterQuantity = () => {
		// 获取水电表详情
		getCurEleAndWaterQuantity({
			roomId: props.id || houseId.value
		}).then((res: any) => {
			baseNumbe.value = res.data

			if (baseNumbe.value.clodWaterMaterStatusName == '在线') {
				modelRef.meters[0].read = baseNumbe.value.coldWaterMaterRead
			}
			if (baseNumbe.value.eleMaterStatusName == '在线') {
				modelRef.meters[3].read = baseNumbe.value.eleMaterRead
			}
			if (baseNumbe.value.hotWaterMaterStatusName == '在线') {
				modelRef.meters[2].read = baseNumbe.value.hotWaterMaterRead
			}
			firstOpen.value = true
		})
	}

	const warehouseIdF = (id: string) => {
		// console.log(, modelData.record)
		if (id) {
			const data = modelData.record
			data.warehouseId = id
			modelRef.transferWhArticles.push(data)
		}
	}

	const handler = (row: any, type: string) => {
		console.log(row)
		modelData.record = row
		switch (type) {
			case 'deployment':
				//修改
				operationField.showDeploy = true
				break
			case 'scrapped':
				//禁用
				console.log(modelData.record.id, 'modelData.record.id')
				operationField.showScrap = true
				console.log('报废')
				break
			case 'lost':
				//启用
				operationField.showLoss = true
				// confirm(row, 1)
				console.log('遗失')
				break
		}
	}
	const gridOptions = reactive<VxeGridProps>({
		size: 'small',
		height: '300px',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: [
			{
				title: '种类',
				minWidth: 100,
				align: 'left',
				field: 'typeName'
			},
			{
				title: '物品名称',
				minWidth: 100,
				align: 'left',
				field: 'configName'
			},
			{
				title: '价格(元)',
				minWidth: 80,
				align: 'left',
				field: 'price'
			},
			{
				title: '数量',
				minWidth: 50,
				align: 'center',
				field: 'count'
			},
			{
				title: '操作',
				width: 120,
				align: 'center',
				slots: {
					default: 'action'
				}
			}
		],
		pagerConfig: {
			autoHidden: true
		},
		proxyConfig: {
			props: {
				message: 'msg',
				result: 'data.articles',
				total: 'data.total'
			},
			ajax: {
				async query() {
					// if (!props.contractId && (props.id || houseId.value)) {
					// 	return houseConfigGetList(props.id || houseId.value)
					// }
					// return {}

					// 新签 续租 换房 转租 props.contractId props.delivery都是为null
					if (
						([1, 2, 4, 3].includes(props.signType as number) || !props.contractId) &&
						(props.id || houseId.value) &&
						!props.delivery && !props.isResubmit
					) {
						//1为业主
						return houseConfigGetList(props.id || houseId.value,1)
					}
					return {}
				}
			}
		}
	})

	const firstOpen = ref<boolean>(false)

	watch([() => props.visible, () => props.id], async (newVal, oldVal) => {
		if (newVal[0]) {
			resetModelRef()

			// if (newVal[1] !== oldVal[1] && newVal[1] !== '' && oldVal[1]) {
			// 	await grid.value.commitProxy('query')
			// }

			if (props.delivery) {
				modelRef.articles = XEUtils.clone(props?.delivery.articles, true) || []
				modelRef.attachmentDtos = XEUtils.clone(props?.delivery.attachmentDtos, true) || []
				modelRef.comment = XEUtils.clone(props?.delivery.comment, true) || ''
				modelRef.attachments = XEUtils.clone(JSON.parse(props?.delivery.attachments), true) || ''
				attachments.value = XEUtils.clone(props?.delivery.attachmentDtos, true) || []
				modelRef.meters = XEUtils.clone(props?.delivery.meters, true) || defaultMeters()
				let timeNumber = setTimeout(() => {
					insertEvent(-1, XEUtils.clone(props?.delivery.articles, true))
					clearTimeout(timeNumber)
				}, 100)
			} else if (props.contractId) {
				getDeliveryGetNoe()
			}else if (
				([1, 2, 4, 3].includes(props.signType as number) || !props.contractId) &&
				(props.id || houseId.value) &&
				!props.delivery&& !props.isResubmit
			) {
				getList()
			}

			// if (props.isCharterSign) {
			// 	houseIndex.value = 0
			// 	enterPriseContracList.value = props.enterPriseContractHouseRoomFroms
			// 	enterPriseContracList.value = props.enterPriseContractHouseRoomFroms.map((e: any) => {
			// 		return {
			// 			...e,
			// 			disabled: !e.isSure,
			// 			address: e.houseAddress + `${e.isSure ? ' - 已确认' : ' - 未确认'}`
			// 		}
			// 	})

			// 	if (!enterPriseContracList.value[houseIndex.value]?.deliveryAddForm) {
			// 		houseId.value = enterPriseContracList.value[houseIndex.value]?.id
			// 		getDeliveryGetNoe()
			// 	} else {
			// 		houseId.value = enterPriseContracList.value[houseIndex.value]?.id
			// 		handlerClick()
			// 	}
			// }

			// if (!firstOpen.value) {
			// 	modelRef.meters = defaultMeters()
			// }
		}
	})

	const getDeliveryGetNoe = () => {
		const params = {
			id: props.contractId || houseId.value,
			type: 1
		}
		getHouseDeliveryGetNoe(params).then((res: any) => {
			if (res.data) {
				modelRef.articles = res.data?.articles || []
				modelRef.attachmentDtos = res.data?.attachmentDtos || []
				modelRef.comment = res.data?.comment || ''
				modelRef.attachments = JSON.parse(res.data?.attachments) || ''
				attachments.value = res.data?.attachmentDtos || []
				modelRef.meters = res?.data.meters || []
				insertEvent(-1, modelRef.articles)
			}
		})
	}
	// 重置表单
	const formRef = ref<any>()

	const checkInNext = () => {
		if (!enterPriseContracList.value[houseIndex.value]?.deliveryAddForm) {
			enterPriseContracList.value[houseIndex.value].isSure = true
			enterPriseContracList.value = enterPriseContracList.value.map((e: any) => {
				return {
					...e,
					disabled: !e.isSure,
					address: e.houseAddress + `${e.isSure ? ' - 已确认' : ' - 未确认'}`
				}
			})
			modelRef.articles = XEUtils.clone(grid.value.getTableData().tableData, true)
			// console.log(modelRef.articles)
			modelRef.attachmentDtos = attachments.value
			// 附件列表id集合
			modelRef.attachments = JSON.stringify(attachments.value.map(o => o.id))
			enterPriseContracList.value[houseIndex.value].deliveryAddForm = {
				...modelRef,
				contractType: 2, // 合同类型-1 个人 2 企业 3 业主
				deliveryType: 1
			}
			if (houseIndex.value < enterPriseContracList.value.length) {
				houseIndex.value++
				houseId.value = enterPriseContracList.value[houseIndex.value]?.id
				getList(1)
				resetModelRef()
				// if (checkList.value) {
				grid.value.remove()
				// }
				getDeliveryGetNoe()
				// setEleAndWaterQuantity()
			}
		} else {
			modelRef.articles = XEUtils.clone(grid.value.getTableData().tableData, true)
			// console.log(modelRef.articles)
			modelRef.attachmentDtos = attachments.value
			// 附件列表id集合
			modelRef.attachments = JSON.stringify(attachments.value.map(o => o.id))
			enterPriseContracList.value[houseIndex.value].deliveryAddForm = {
				...modelRef,
				contractType: 2, // 合同类型-1 个人 2 企业 3 业主
				deliveryType: 1
			}

			houseIndex.value++
			houseId.value = enterPriseContracList.value[houseIndex.value]?.id
			// if (checkList.value) {
			// }
			console.log(enterPriseContracList.value[houseIndex.value])
			console.log(enterPriseContracList.value)
			resetModelRef()
			grid.value.remove()
			// 回显
			handlerClick()
		}
	}

	const handlerChange = (e: string) => {
		resetModelRef()
		// if (checkList.value) {
		grid.value.remove()
		// }

		houseId.value = e
		let data = enterPriseContracList.value.find((o: any) => o.id == e)
		houseIndex.value = enterPriseContracList.value.findIndex((o: any) => o.id == e)
		modelRef.articles = XEUtils.clone(data?.deliveryAddForm?.articles, true) || []
		modelRef.attachmentDtos = XEUtils.clone(data?.deliveryAddForm?.attachmentDtos, true) || []
		modelRef.comment = XEUtils.clone(data?.deliveryAddForm?.comment, true) || ''
		modelRef.attachments = XEUtils.clone(JSON.parse(data?.deliveryAddForm?.attachments), true) || []
		attachments.value = XEUtils.clone(data?.deliveryAddForm?.attachmentDtos, true) || []
		modelRef.meters = XEUtils.clone(data?.deliveryAddForm?.meters, true) || defaultMeters()

		let timeNumber = setTimeout(() => {
			insertEvent(-1, XEUtils.clone(data?.deliveryAddForm?.articles, true))
			clearTimeout(timeNumber)
		}, 100)
	}

	// 完成并保存
	const completeSave = () => {
		enterPriseContracList.value[houseIndex.value].isSure = true
		enterPriseContracList.value = enterPriseContracList.value.map((e: any) => {
			return {
				...e,
				disabled: !e.isSure,
				address: e.houseAddress + `${e.isSure ? ' - 已确认' : ' - 未确认'}`
			}
		})
		modelRef.articles = XEUtils.clone(grid.value.getTableData().tableData, true)
		// console.log(modelRef.articles)
		modelRef.attachmentDtos = attachments.value

		// 附件列表id集合
		modelRef.attachments = JSON.stringify(attachments.value.map(o => o.id))
		enterPriseContracList.value[houseIndex.value].deliveryAddForm = {
			...modelRef,
			contractType: 2, // 合同类型-1 个人 2 企业 3 业主
			deliveryType: 1
		}

		emit('success', enterPriseContracList.value)
		houseIndex.value = 0
		houseId.value = ''
		checkList.value = []
		grid.value.remove()
		emit('update:visible', false)
	}

	const handlerClick = () => {
		if (!enterPriseContracList.value[houseIndex.value]?.deliveryAddForm) return
		resetModelRef()
		// if (checkList.value) {
		grid.value.remove()
		// }
		console.log(
			enterPriseContracList.value[houseIndex.value]?.deliveryAddForm,
			'enterPriseContracList.value[houseIndex.value]?.deliveryAddForm?'
		)
		modelRef.articles = XEUtils.clone(enterPriseContracList.value[houseIndex.value]?.deliveryAddForm?.articles, true) || []

		modelRef.attachmentDtos = XEUtils.clone(enterPriseContracList.value[houseIndex.value]?.deliveryAddForm?.attachmentDtos, true) || []
		modelRef.comment = XEUtils.clone(enterPriseContracList.value[houseIndex.value]?.deliveryAddForm?.comment, true) || ''
		if (enterPriseContracList.value[houseIndex.value]?.deliveryAddForm) {
			modelRef.attachments =
				XEUtils.clone(JSON.parse(enterPriseContracList.value[houseIndex.value]?.deliveryAddForm?.attachments), true) || []
		} else {
			modelRef.attachments = []
		}

		attachments.value = XEUtils.clone(enterPriseContracList.value[houseIndex.value]?.deliveryAddForm?.attachmentDtos, true) || []
		modelRef.meters = XEUtils.clone(enterPriseContracList.value[houseIndex.value]?.deliveryAddForm?.meters, true) || defaultMeters()
		let timeNumber = setTimeout(() => {
			insertEvent(-1, XEUtils.clone(enterPriseContracList.value[houseIndex.value]?.deliveryAddForm?.articles, true))
			clearTimeout(timeNumber)
		}, 100)
	}

	const prompt = () => {
		Modal.confirm({
			title: '提示',
			centered: true,
			icon: createVNode(ExclamationCircleOutlined),
			content: '您正在退出物业交割单填写,退出后已填写内容暂未保存,再次提交时需要重新填写,请确定是否退出?',
			okText: '继续填写',
			cancelText: '已知悉,确认退出',
			onOk() {},
			onCancel() {
				if (checkList.value) {
					grid.value.remove(checkList.value)
				}
				Object.keys(operationField).forEach(key => {
					operationField[key] = false
				})
				houseIndex.value = 0
				houseId.value = ''
				grid.value.remove()
				emit('update:visible', false)
			}
		})
	}
</script>
<style lang="less">
	.bill-box {
		// position: fixed;
		display: flex;
		justify-content: space-around;
		margin-bottom: 10px;
		.select {
			width: 888px;
		}
	}
	.width-33 {
		width: 33.33%;
	}
	.delivery-note .ant-modal-content {
		.ant-modal-body {
			height: 600px;
			overflow-y: auto;
		}

		.tab-box {
			position: relative;

			.right-btn {
				position: absolute;
				right: 0;
				top: 0;
			}
		}

		.d-module-title {
			margin-bottom: 5px;
		}
		.delivery-note-module {
			margin-bottom: 20px;
		}
	}
</style>
